package com.ethan.cj.ssm.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 尝试使用AOP处理get请求乱码
 * 结果失败，不存在IOC容器中，无法注入
 */
@Aspect
@Component
public class EncodingFilterAOP {
    @Pointcut("execution(* javax.servlet.http.HttpServletRequestWrapper.getParameter())")
    public void getParameter() {}

    @Pointcut("execution(* javax.servlet.http.HttpServletRequestWrapper.getParameterValues())")
    public void getParameterValues() {}

    @Around("getParameter()")
    public Object aroundGetParameter(ProceedingJoinPoint pjp) throws Throwable {
        Object object = pjp.proceed();
        if (object == null) return null;
        if (object instanceof String) {
            String s = (String) object;
            s = new String(s.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            return s;
        }
        return object;
    }

    @Around("getParameterValues()")
    public Object aroundGetParameterValues(ProceedingJoinPoint pjp) throws Throwable {
        Object object = pjp.proceed();
        if (object == null) return null;
        if (object instanceof String[]) {
            String[] s = (String[]) object;
            for (int i = 0; i < s.length; i++) {
                s[i] = new String(s[i].getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            }
            return s;
        }
        return object;
    }


}
